package com.cx.common.gateway.filter.pre;

import com.cx.common.core.constant.Constants;
import com.cx.common.core.utils.StringUtils;
import com.cx.common.core.utils.uuid.UUID;
import com.cx.common.gateway.filter.AbstractFilter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author _
 * @date 2021/8/6
 */
@Component
@Slf4j
public class RequestGatewayGlobalFilter extends AbstractFilter implements Ordered {

    protected RequestGatewayGlobalFilter(RouteLocator routeLocator) {
        super(routeLocator);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String traceId = request.getHeaders().getFirst(Constants.TRACE_ID);
        if (StringUtils.isEmpty(traceId)) {
            traceId = UUID.fastUUID().toString(true);
        }
        MDC.put(Constants.TRACE_ID, traceId);

        response.getHeaders().set(Constants.TRACE_ID, traceId);
        ServerWebExchange build = exchange.mutate()
                .request(request.mutate().header(Constants.TRACE_ID, traceId).build())
                .build();
        return chain.filter(build);
    }

    @Override
    public Mono<Void> run(ServerWebExchange exchange, GatewayFilterChain chain) {
        return Mono.empty();
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
